/**
 * 
 */
package com.itinsys.enma.service.mail.impl;

import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;

import com.itinsys.enma.service.mail.MailService;
import com.sun.mail.smtp.SMTPTransport;

/**
 * @author pferraz
 *
 */
public class MailServiceImpl implements MailService {
	
	private static Logger logger=Logger.getLogger("service");
	
	@Value("#{phProperties.mailServer}")
	private String server;
	@Value("#{phProperties.mailFrom}")
	private String from;
	
	public boolean sendMail(String to,String subject,String description){
		boolean result=false;
		try {
			Session mailSession = Session.getInstance(System.getProperties());
			Transport transport = new SMTPTransport(mailSession, new URLName(server));
			transport.connect(server, 25, null, null);
			MimeMessage m = new MimeMessage(mailSession);
			m.setFrom(new InternetAddress(from));
			Address[] toAddr = new InternetAddress[] { new InternetAddress(to) };
			m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr);
			m.setSubject(subject);
			m.setSentDate(new java.util.Date());
			m.setContent(description, "text/plain");
			transport.sendMessage(m, m.getAllRecipients());
			transport.close();
			logger.info("Mail enviado");
			
			result=true;
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		
		return result;
	}
}
